<template>
	<view class="container">
		<view class="page-title">我的需求</view>
		
		<!-- 发布新需求按钮 -->
		<view class="action-bar">
			<button class="btn-primary" @click="goToCreate">发布新需求</button>
		</view>
		
		<!-- 需求列表 -->
		<scroll-view class="scroll-area" 
					 scroll-y="true" 
					 @scrolltolower="loadMore"
					 refresher-enabled="true"
					 @refresherrefresh="refresh"
					 :refresher-triggered="refreshing">
			<view v-for="item in demandList" :key="item.id" class="list-item">
				<view class="item-header">
					<text class="item-title">{{ item.description }}</text>
					<view class="item-status" :class="getStatusClass(item.status)">
						{{ getStatusText(item.status) }}
					</view>
				</view>
				
				<view class="item-content">
					<text class="item-quantity">需求量：{{ item.quantity }} {{ item.quantityUnit }}</text>
					<text class="item-time">发布时间：{{ item.createTime }}</text>
					
					<view v-if="item.image1" class="item-images">
						<image class="item-image" :src="item.image1" mode="aspectFill"></image>
						<image v-if="item.image2" class="item-image" :src="item.image2" mode="aspectFill"></image>
						<image v-if="item.image3" class="item-image" :src="item.image3" mode="aspectFill"></image>
					</view>
				</view>
				
				<view v-if="item.contactName || item.contactPhone" class="item-contact">
					<text v-if="item.contactName">联系人：{{ item.contactName }}</text>
					<text v-if="item.contactPhone">电话：{{ item.contactPhone }}</text>
				</view>
				
				<view class="item-actions">
					<button class="btn-small btn-primary" @click="viewMatches(item)">查看撮合</button>
					<button v-if="item.status === 1" class="btn-small btn-danger" @click="cancelDemand(item)">取消需求</button>
				</view>
			</view>
			
			<view v-if="demandList.length === 0 && !loading" class="empty-tip">
				您还没有发布过需求
				<button class="btn-primary" @click="goToCreate">立即发布</button>
			</view>
			
			<view v-if="loading" class="loading-tip">
				加载中...
			</view>
		</scroll-view>
	</view>
</template>

<script>
import { api } from '../../utils/request.js';
import authStore from '../../store/auth.js';

export default {
	data() {
		return {
			// 需求列表
			demandList: [],
			
			// 分页参数
			pageNo: 1,
			pageSize: 10,
			hasMore: true,
			
			// 加载状态
			loading: false,
			refreshing: false,
			
			// 当前用户
			currentUser: null
		}
	},
	
	onLoad() {
		// 我的需求页面：买家查看自己发布的需求列表
		// 需要登录验证，接口：GET /api/demand/my-demands
		this.checkAuth();
	},
	
	onShow() {
		// 每次显示页面时刷新数据
		if (authStore.isLoggedIn()) {
			this.refresh();
		}
	},
	
	methods: {
		// 检查登录状态
		async checkAuth() {
			if (!authStore.isLoggedIn()) {
				try {
					await authStore.loginWithWeixin();
					this.currentUser = authStore.getCurrentUser();
					this.loadDemandList();
				} catch (error) {
					uni.showModal({
						title: '提示',
						content: '需要登录后才能查看需求',
						success: (res) => {
							if (res.confirm) {
								uni.switchTab({ url: '/pages/user/index' });
							} else {
								uni.navigateBack();
							}
						}
					});
				}
			} else {
				this.currentUser = authStore.getCurrentUser();
				this.loadDemandList();
			}
		},
		
		// 跳转到发布需求页面
		goToCreate() {
			uni.navigateTo({ url: '/pages/demand/create' });
		},
		
		// 加载需求列表
		async loadDemandList(isRefresh = false) {
			if (this.loading) return;
			if (!isRefresh && !this.hasMore) return;
			
			this.loading = true;
			
			try {
				const pageNo = isRefresh ? 1 : this.pageNo;
				const params = {
					pageNo: pageNo,
					pageSize: this.pageSize
				};
				
				// 添加用户ID参数
				if (this.currentUser && this.currentUser.id) {
					params.userId = this.currentUser.id;
				}
				
				const response = await api.get('/api/demand/my-demands', params, true);
				const { list, total } = response;
				
				if (isRefresh) {
					this.demandList = list || [];
					this.pageNo = 1;
				} else {
					this.demandList = this.demandList.concat(list || []);
				}
				
				// 判断是否还有更多数据
				this.hasMore = this.demandList.length < total;
				if (!isRefresh) {
					this.pageNo++;
				}
				
			} catch (error) {
				console.error('加载我的需求失败:', error);
			} finally {
				this.loading = false;
				this.refreshing = false;
			}
		},
		
		// 下拉刷新
		refresh() {
			this.refreshing = true;
			this.hasMore = true;
			this.loadDemandList(true);
		},
		
		// 上拉加载更多
		loadMore() {
			this.loadDemandList(false);
		},
		
		// 获取状态文本
		getStatusText(status) {
			const statusMap = {
				1: '进行中',
				2: '已完成',
				3: '已取消'
			};
			return statusMap[status] || '未知状态';
		},
		
		// 获取状态样式类
		getStatusClass(status) {
			const classMap = {
				1: 'status-active',
				2: 'status-completed',
				3: 'status-cancelled'
			};
			return classMap[status] || '';
		},
		
		// 查看撮合情况
		viewMatches(demand) {
			// 跳转到撮合中心，传递需求ID
			uni.navigateTo({ 
				url: `/pages/match/index?demandId=${demand.id}&type=buyer`
			});
		},
		
		// 取消需求
		cancelDemand(demand) {
			uni.showModal({
				title: '确认取消',
				content: '确定要取消这个需求吗？取消后将无法恢复。',
				success: async (res) => {
					if (res.confirm) {
						try {
							// 这里假设有取消需求的接口，实际根据后端API调整
							await api.post(`/api/demand/${demand.id}/cancel`, {}, true);
							
							uni.showToast({
								title: '取消成功',
								icon: 'success'
							});
							
							// 刷新列表
							this.refresh();
							
						} catch (error) {
							console.error('取消需求失败:', error);
						}
					}
				}
			});
		}
	}
}
</script>

<style scoped>
.action-bar {
	padding: 20rpx;
	text-align: center;
	background: white;
	margin-bottom: 20rpx;
}

.scroll-area {
	height: calc(100vh - 200rpx);
}

.item-header {
	display: flex;
	justify-content: space-between;
	align-items: flex-start;
	margin-bottom: 20rpx;
}

.item-title {
	font-size: 30rpx;
	font-weight: bold;
	color: #333;
	flex: 1;
	margin-right: 20rpx;
}

.item-status {
	padding: 8rpx 16rpx;
	border-radius: 20rpx;
	font-size: 24rpx;
	color: white;
}

.status-active {
	background-color: #007aff;
}

.status-completed {
	background-color: #4cd964;
}

.status-cancelled {
	background-color: #999;
}

.item-content {
	margin-bottom: 20rpx;
}

.item-quantity {
	font-size: 28rpx;
	color: #666;
	display: block;
	margin-bottom: 10rpx;
}

.item-time {
	font-size: 26rpx;
	color: #999;
	display: block;
	margin-bottom: 15rpx;
}

.item-images {
	display: flex;
	gap: 10rpx;
	margin-top: 20rpx;
}

.item-image {
	width: 80rpx;
	height: 80rpx;
	border-radius: 8rpx;
}

.item-contact {
	font-size: 26rpx;
	color: #999;
	margin-bottom: 20rpx;
}

.item-contact text {
	display: block;
	margin-bottom: 5rpx;
}

.item-actions {
	display: flex;
	gap: 20rpx;
	justify-content: flex-end;
}

.btn-small {
	padding: 15rpx 30rpx;
	font-size: 26rpx;
	border-radius: 6rpx;
	border: none;
}

.empty-tip {
	text-align: center;
	color: #999;
	padding: 80rpx 40rpx;
	font-size: 28rpx;
}

.empty-tip button {
	margin-top: 40rpx;
}

.loading-tip {
	text-align: center;
	color: #666;
	padding: 30rpx 0;
	font-size: 28rpx;
}
</style>